﻿using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using Dapper;

namespace GMS.DataAccessDapper
{
    public class DapperUtil
    {
        private readonly IConfiguration _configuration;

        private IDbConnection _db;

        public IDbConnection Db
        {
            get { return _db ??= new SqlConnection(_configuration.GetConnectionString("DefaultConnString")); }
        }

        public DapperUtil(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 执行Sql语句并返回影响条数
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<int> ExecuteAsync(string strSql, object parameter = null)
        {
            return await Db.ExecuteAsync(strSql, parameter);
        }

        /// <summary>
        /// 执行Sql语句并返回List数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSql"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<IEnumerable<T>> QueryMultipleAsync<T>(string strSql, object parameter = null)
        {
            return await Db.QueryAsync<T>(strSql, parameter);
        }

        /// <summary>
        /// 执行Sql语句并返回单个数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSql"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<T> QuerySingleAsync<T>(string strSql, object parameter = null)
        {
            return await Db.QueryFirstOrDefaultAsync<T>(strSql, parameter);
        }

        public async Task<object> ExecuteScalarAsync(string strSql, object parameter = null)
        {
            return await Db.ExecuteScalarAsync(strSql, parameter);
        }

    }
}
